package cn.otrue.patienthealthmanager.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.achartengine.GraphicalView;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.LoginActivity;
import cn.otrue.patienthealthmanager.adapter.HorizontalAdapter;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.view.ChartViewProdutor;
import cn.otrue.patienthealthmanager.view.HorizontalListView;
import cn.otrue.patienthealthmanager.view.PagerScrollView;
import cn.otrue.patienthealthmanager.view.StatisticsPopupWindow;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

/**
 * 首页->历史数据
 * 
 * @author G
 * 
 */
public class MainHistoryDataFragment extends BaseFragment implements
		OnTouchListener {

	private GraphicalView mChartView;
	/** 弹出框的参考View */
	public TextView tv_catt_right;
	private int timeScope = MyConst.CHART_DAYS;
	private LinearLayout ll_catt_pluspressure_chart_view;
	private LinearLayout ll_catt_sugar_chart_view;

	private HorizontalListView catt_hor_list;
	private TextView tv_sugar_statistics;

	private TextView tv_pluspressure_statistics;

	private StatisticsPopupWindow popupWindow;
	private View rootView;
	private LinearLayout main_history_ll;
	private SimpleDateFormat formatBuilder;
	private List<Map<String, String>> heartData;

	private DatePickerDialog sugarPickerDialog;
	private DatePickerDialog datePickerDialog;
	private String sugarBeginTime;
	private String sugarEndTime;

	private TextView tv_other_statistics;
	private AlertDialog alertDialog;
	private String otherBeginTime;
	private String otherEndTime;
	private Calendar plusBeginCalendar = Calendar.getInstance();
	private Calendar plusEndCalendar = Calendar.getInstance();

	private Calendar otherBeginCalendar = Calendar.getInstance();
	private Calendar otherEndCalendar = Calendar.getInstance();

	private Calendar sugarBeginCalendar = Calendar.getInstance();
	private Calendar sugarEndCalendar = Calendar.getInstance();

	private String plusBeginTime;
	private String plusEndTime;

	private EditText et_sugar_begin_time;
	private EditText et_sugar_end_time;
	private EditText et_pluspressure_begin_time;
	private EditText et_pluspressure_end_time;
	private EditText et_other_begin_time;
	private EditText et_other_end_time;
	private boolean isSugarDay;// 是否是单天的血糖数据：用于统计
	private boolean isplus_heart_Day;// 是否是单天的血压心率
	// ////////////////////////////////////Handler//////////////////////////////////////////
	// 血糖
	private Handler sugarHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Log.e("history", "sugar" + dataStr);
				List<Map<String, String>> sugarData = HttpServer.gson.fromJson(
						dataStr, new TypeToken<List<Map<String, String>>>() {
						}.getType());
				if (sugarData != null && sugarData.size() > 0) {
					changeChart(sugarData, MyConst.SUGAR, false);
				} else {
					Toast.makeText(MainHistoryDataFragment.this.getActivity(),
							"暂无数据", 0).show();
				}
			} else {

			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			super.onFail(data, state);
		}

	};

	// 血压
	private Handler pressureHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			if (state.equals(HttpCons.STATE_SUCCESS)) {

				String dataStr = data.getString(HttpCons.DATA);
				Log.e("hhttp", "pressure" + dataStr);
				List<Map<String, String>> pressureData = HttpServer.gson
						.fromJson(dataStr,
								new TypeToken<List<Map<String, String>>>() {
								}.getType());
				if (pressureData != null && heartData != null) {
					changeChart(pressureData, MyConst.PLUS_PRESSURE, false);
				} else {
					Toast.makeText(MainHistoryDataFragment.this.getActivity(),
							"暂无数据", 0).show();
				}
			} else {

			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}
	};

	// 心率
	private Handler heartHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals(HttpCons.STATE_SUCCESS)) {

				String dataStr = data.getString(HttpCons.DATA);
				Log.e("hhttp", "heart" + dataStr);
				heartData = HttpServer.gson.fromJson(dataStr,
						new TypeToken<List<Map<String, String>>>() {
						}.getType());
				if (heartData != null) {
					getPressure();
				} else {
					Toast.makeText(MainHistoryDataFragment.this.getActivity(),
							"暂无数据", 0).show();
				}
			} else {

			}

		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}

	};

	// 其他
	private Handler otherHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			if (state.equals(HttpCons.STATE_SUCCESS)) {

				String dataStr = data.getString(HttpCons.DATA);
				Log.e("hhttp", "otherHandler" + dataStr);
				List<Map<String, String>> listMap = HttpServer.gson.fromJson(
						dataStr, new TypeToken<List<Map<String, String>>>() {
						}.getType());
				if (listMap != null && listMap.size() > 0) {
					List<Map<String, Object>> finalData = new ArrayList<Map<String, Object>>();
					// /////////////////////////////////////////////////////////////////////////////
					HashMap<String, Object> hashMap = new HashMap<String, Object>();

					try {
						hashMap.put("diseasetime", CommonUtil.long2DateStr(Long
								.parseLong(listMap.get(0).get("diseasetime"))));
					} catch (NumberFormatException e) {
						hashMap.put(
								"diseasetime",
								listMap.get(0).get("diseasetime")
										.substring(0, 10));
					}

					hashMap.put("diseaselist", new ArrayList());
					finalData.add(hashMap);

					// ////////////////////////////////////////////////

					for (int i = 0; i < listMap.size(); i++) {
						String diseasetime = CommonUtil.long2DateStr(Long
								.parseLong(listMap.get(i).get("diseasetime")));
						boolean b = true;
						for (int j = 0; j < finalData.size(); j++) {

							if (diseasetime.equals(finalData.get(j).get(
									"diseasetime"))) {
								b = false;
							}

						}
						if (b) {
							HashMap<String, Object> eachMap = new HashMap<String, Object>();
							eachMap.put("diseasetime", diseasetime);
							eachMap.put("diseaselist", new ArrayList<String>());
							finalData.add(eachMap);
						}

					}

					System.out.println(finalData.toString());

					for (int i = 0; i < listMap.size(); i++) {
						String diseasetime = CommonUtil.long2DateStr(Long
								.parseLong(listMap.get(i).get("diseasetime")));
						String diseasename = listMap.get(i).get("diseasename");

						for (int j = 0; j < finalData.size(); j++) {
							if (diseasetime.equals(finalData.get(j).get(
									"diseasetime"))) {
								((List<String>) finalData.get(j).get(
										"diseaselist")).add(diseasename);
								break;
							}
						}

					}

					Collections.sort(finalData,
							new Comparator<Map<String, Object>>() {
								public int compare(Map<String, Object> arg0,
										Map<String, Object> arg1) {
									return arg0
											.get("diseasetime")
											.toString()
											.compareTo(
													arg1.get("diseasetime")
															.toString());
								}
							});

					catt_hor_list.setAdapter(new HorizontalAdapter(
							MainHistoryDataFragment.this.getActivity(),
							finalData, popupWindow, main_history_ll,
							isSugarDay, isplus_heart_Day));
				}

			} else {
				Toast.makeText(MainHistoryDataFragment.this.getActivity(), msg,
						0).show();
			}

		}

		@Override
		public void onFail(Bundle data, String state) {
			super.onFail(data, state);
		}

	};

	private Handler oneDayAllHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Log.e("history", "oneDay" + dataStr);

				JsonObject o = new JsonParser().parse(dataStr)
						.getAsJsonObject();

				String BloodCollectionStr = HttpServer.gson.toJson(o
						.get("BloodCollection"));

				String heartRateStr = HttpServer.gson
						.toJson(o.get("heartRate"));
				String CollectionOfBloodPressureStr = HttpServer.gson.toJson(o
						.get("CollectionOfBloodPressure"));

				List<Map<String, String>> bloodCollection = HttpServer.gson
						.fromJson(BloodCollectionStr,
								new TypeToken<List<Map<String, String>>>() {
								}.getType());

				if (isSugar && bloodCollection != null
						&& bloodCollection.size() > 0) {
					changeChart(bloodCollection, MyConst.SUGAR, true);
				}

				List<Map<String, String>> heartRate = HttpServer.gson.fromJson(
						heartRateStr,
						new TypeToken<List<Map<String, String>>>() {
						}.getType());
				List<Map<String, String>> CollectionOfBloodPressure = HttpServer.gson
						.fromJson(CollectionOfBloodPressureStr,
								new TypeToken<List<Map<String, String>>>() {
								}.getType());

				if (isPlus && heartRate != null
						&& CollectionOfBloodPressure != null
						&& CollectionOfBloodPressure.size() > 0) {
					heartData = heartRate;
					changeChart(CollectionOfBloodPressure,
							MyConst.PLUS_PRESSURE, true);
				}

			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}
	};

	private Handler sugarStatisticsHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			Log.e("hdata", state + "  " + msg);
			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Map<String, String> map = HttpServer.gson.fromJson(dataStr,
						new TypeToken<Map<String, String>>() {
						}.getType());
				String[] sugarData = new String[14];

				sugarData[0] = map.get("BeforeAMealAndHighPressure");
				sugarData[1] = map.get("normalBloodSugarNumber");
				sugarData[2] = map.get("bloodSugarIsLowPercentage");
				sugarData[3] = map.get("highBloodSugarPercentage");
				sugarData[4] = map.get("TheAverageMealBefore");
				sugarData[5] = map.get("AfterTheMealLowPressure");
				sugarData[6] = map.get("bloodSugarIsLowFrequency");
				sugarData[7] = map.get("normalBloodSugarPercentage");
				sugarData[8] = map.get("afterTheMealAndHighPressure");
				sugarData[9] = map.get("numberOfBloodSugarOnTheHighSide");
				sugarData[10] = map.get("ThePercentageOfNormal");
				sugarData[11] = map.get("LowPressureBeforeMeal");
				sugarData[12] = map.get("AfterEatingANormalPercentage");
				sugarData[13] = map.get("AfterTheMealAverage");
				statisticsSugar(MyConst.SUGAR, sugarData);
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			super.onFail(data, state);
		}
	};

	private Handler plusPressureStatisticsHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Map<String, String> map = HttpServer.gson.fromJson(dataStr,
						new TypeToken<Map<String, String>>() {
						}.getType());
				String[] plusData = new String[20];
				plusData[0] = map.get("theLowestBloodPressureValues");// 根据账号查询指定时间最低的血压值
				plusData[1] = map.get("theavgBloodPressureValues");// 根据账号查询指定时间平均的血压值
				plusData[2] = map.get("TheHeartRateAbnormalPercentage");// 心率百分比
				plusData[3] = map.get("lowHeartrate");// 根据账号查询指定时间最低的心率值
				plusData[4] = map.get("highHeartRatePercentage");// 高心率百分比
				plusData[5] = map.get("HeartRateIsLowPercentage");// 心率较低的百分比
				plusData[6] = map.get("numberOfHeartRateOnTheHighSide");// 根据账号
																		// 查询指定时间心率的偏高次数
				plusData[7] = map.get("theHighestBloodPressureValues");// 根据账号查询指定时间的血压最高血压值
				plusData[8] = map.get("normalHeartRateNumber");// 根据账号
																// 查询出患者指定时间心率正常值总次数
				plusData[9] = map.get("avgHeartrate");// 根据账号查询指定时间平均的心率值
				plusData[10] = map.get("bloodPressIsLowFrequency");// 根据账号
																	// 查询指定时间血压的偏低次数
				plusData[11] = map.get("bloodPressIsLowPercentage");// 血压偏低百分比
				plusData[12] = map.get("heightHeartrate");// 偏高心率
				plusData[13] = map.get("HeartRateIsLowFrequency");// 根据账号
																	// 查询指定时间心率的偏低次数
				plusData[14] = map.get("OfTheTotalOfBloodPressureIsNormal");// 血压正常次数
				plusData[15] = map.get("PercentageOfPartialHighBloodPressure ");// 血压偏高百分比
				plusData[16] = map.get("PartialBloodPressureValues");// 偏高血压次数
				plusData[17] = map.get("BloodPressureIsNormalPercentage");// 血压正常百分比
				plusData[18] = map.get("normalHeartRatePercentage");// 心率正常百分比
				plusData[19] = map.get("AbnormalBloodPressurePercentage");// 血压百分比
				statisticsSugar(MyConst.PLUS_PRESSURE, plusData);
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}
	};

	private Handler otherStatisticsHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataStr = data.getString(HttpCons.DATA);
				Map<String, String> map = HttpServer.gson.fromJson(dataStr,
						new TypeToken<Map<String, String>>() {
						}.getType());
				String[] otherData = new String[4];

				// 其它正常
				otherData[0] = map.get("normal");
				// 其它异常
				otherData[1] = map.get("exception");

				statisticsSugar(MyConst.OTHER, otherData);
			}
		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}
	};

	// ////////////////////////////////////Handler_end//////////////////////////////////////////

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		formatBuilder = new SimpleDateFormat("MM.dd");
		rootView = inflater.inflate(R.layout.fragment_main_history, null);
		initView(rootView);

		return rootView;
	}

	private void initView(View rootView) {

		main_history_ll = (LinearLayout) rootView
				.findViewById(R.id.main_history_ll);

		// 初始化图表
		ll_catt_sugar_chart_view = (LinearLayout) rootView
				.findViewById(R.id.ll_catt_sugar_chart_view);
		ll_catt_pluspressure_chart_view = (LinearLayout) rootView
				.findViewById(R.id.ll_catt_pluspressure_chart_view);
		catt_hor_list = (HorizontalListView) rootView
				.findViewById(R.id.catt_hor_list);

		tv_sugar_statistics = (TextView) rootView
				.findViewById(R.id.tv_sugar_statistics);
		et_sugar_begin_time = (EditText) rootView
				.findViewById(R.id.et_sugar_begin_time);
		et_sugar_end_time = (EditText) rootView
				.findViewById(R.id.et_sugar_end_time);
		tv_pluspressure_statistics = (TextView) rootView
				.findViewById(R.id.tv_pluspressure_statistics);
		et_pluspressure_begin_time = (EditText) rootView
				.findViewById(R.id.et_pluspressure_begin_time);
		et_pluspressure_end_time = (EditText) rootView
				.findViewById(R.id.et_pluspressure_end_time);
		tv_other_statistics = (TextView) rootView
				.findViewById(R.id.tv_other_statistics);
		et_other_begin_time = (EditText) rootView
				.findViewById(R.id.et_other_begin_time);
		et_other_end_time = (EditText) rootView
				.findViewById(R.id.et_other_end_time);

		tv_sugar_statistics.setOnClickListener(this);
		tv_pluspressure_statistics.setOnClickListener(this);
		tv_other_statistics.setOnClickListener(this);

		et_sugar_begin_time.setOnClickListener(this);
		et_sugar_end_time.setOnClickListener(this);
		et_pluspressure_begin_time.setOnClickListener(this);
		et_pluspressure_end_time.setOnClickListener(this);
		et_other_begin_time.setOnClickListener(this);
		et_other_end_time.setOnClickListener(this);

		this.isInitViewCompleted = true;
		isSugarDay = true;
		isplus_heart_Day = true;
	}

	// 修改图表
	private void changeChart(List<Map<String, String>> list, int type,
			boolean isOneDay) {
		CommonUtil.listRemoveNull(list);
		switch (type) {

		case MyConst.SUGAR:
			List<String> sugarDateList = new ArrayList<String>();
			List<Double> sugarBe = new ArrayList<Double>();
			List<Double> sugarAf = new ArrayList<Double>();

			Collections.sort(list, new Comparator<Map<String, String>>() {
				public int compare(Map<String, String> arg0,
						Map<String, String> arg1) {
					return arg0.get("measure").compareTo(arg1.get("measure"));
				}
			});
			List<Map<String, String>> finalSugarData = new ArrayList<Map<String, String>>();
			if (!isOneDay) {
				for (int i = 0; i < list.size(); i++) {
					Map<String, String> eachMap = list.get(i);

					if (eachMap.containsKey("bloodvalue")) {
						boolean b = false;
						int cid = 0;
						for (int j = 0; j < finalSugarData.size(); j++) {
							if (finalSugarData
									.get(j)
									.get("measure")
									.equals(eachMap.get("measure").substring(0,
											10))) {
								b = true;
								cid = j;
								break;
							}
						}
						if (b) {
							if (eachMap.get("flag").equals("0")) {
								finalSugarData.get(cid).put("aSugar",
										eachMap.get("bloodvalue"));

							} else {
								finalSugarData.get(cid).put("bSugar",
										eachMap.get("bloodvalue"));
							}
						} else {
							HashMap<String, String> eachSugarMap = new HashMap<String, String>();
							eachSugarMap.put("measure", eachMap.get("measure")
									.substring(0, 10));
							if (eachMap.get("flag").equals("0")) {
								eachSugarMap.put("aSugar",
										eachMap.get("bloodvalue"));
								eachSugarMap.put("bSugar", "0");
							} else {
								eachSugarMap.put("bSugar",
										eachMap.get("bloodvalue"));
								eachSugarMap.put("aSugar", "0");
							}

							finalSugarData.add(eachSugarMap);
						}
					}

				}

			} else {
				for (int i = 0; i < list.size(); i++) {
					Map<String, String> eachMap = list.get(i);

					if (eachMap.containsKey("bloodvalue")) {

						sugarDateList.add(CommonUtil.getFormatDate(
								"HH:mm",
								new Date(Long.parseLong(list.get(i).get(
										"measure")))));
						double bloodvalue = Double.parseDouble(eachMap
								.get("bloodvalue"));
						if (bloodvalue > 12) {
							bloodvalue = 12;
						}
						if (eachMap.get("flag").equals("0")) {

							sugarAf.add(bloodvalue);

						} else {
							sugarBe.add(bloodvalue);

						}
					}

				}

			}
			List<double[]> values = new ArrayList<double[]>();
			double[] sugarBeArr = new double[60];
			// double[] sugarBEArrOver=new double[60];
			double[] sugarAfArr = new double[60];
			// double[] sugarAfArrOver=new double[60];

			if (!isOneDay) {

				for (int i = 0; i < finalSugarData.size(); i++) {
					Map<String, String> eachMap = finalSugarData.get(i);
					sugarDateList.add(eachMap.get("measure"));

					sugarAfArr[i] = Double.parseDouble(eachMap.get("aSugar"));
					sugarBeArr[i] = Double.parseDouble(eachMap.get("bSugar"));

				}
			} else {
				for (int i = 0; i < sugarBe.size(); i++) {
					sugarBeArr[i] = sugarBe.get(i);

				}
				for (int i = 0; i < sugarAf.size(); i++) {
					sugarAfArr[i] = sugarAf.get(i);
				}
			}
			values.add(sugarAfArr);
			values.add(sugarBeArr);
			ll_catt_sugar_chart_view.removeAllViews();
			if(values!=null&&values.size()>0) {
				mChartView = new ChartViewProdutor(rootView.getContext())
						.getBloodChart(values, sugarDateList);
				ll_catt_sugar_chart_view.addView(mChartView);
			}

			break;

		case MyConst.PLUS_PRESSURE:

			// 日期
			List<String> heartDateList = new ArrayList<String>();

			// 心率值heartData 血压值list
			List<Map<String, String>> allList = new ArrayList<Map<String, String>>();
			allList.addAll(heartData);
			allList.addAll(list);

			if (allList != null && allList.size() > 0) {

				int endLength = 0;
				int showStartLength = 0;
				if (isOneDay) {
					for (int i = 0; i < allList.size(); i++) {

						String dateTime = CommonUtil.getFormatDate(
								"HH:mm",
								new Date(Long.parseLong(allList.get(i).get(
										"measuretime"))));
						allList.get(i).put("measuretime", dateTime);
					}
					endLength = allList.get(0).get("measuretime").length();
				} else {
					endLength = 10;
					showStartLength = 5;
				}

				List<Map<String, String>> finalList = new ArrayList<Map<String, String>>();
				Map<String, String> hashmap = new HashMap<String, String>();
				hashmap.put("measuretime", allList.get(0).get("measuretime")
						.substring(0, endLength));
				finalList.add(hashmap);

				for (int i = 0; i < allList.size(); i++) {
					String measuretime = allList.get(i).get("measuretime")
							.substring(0, endLength);
					boolean b = true;
					for (int j = 0; j < finalList.size(); j++) {

						if (measuretime.equals(finalList.get(j).get(
								"measuretime"))) {
							b = false;
						}
					}
					if (b) {
						Map<String, String> eachMap = new HashMap<String, String>();
						eachMap.put("measuretime", measuretime);
						finalList.add(eachMap);
					}
				}

				for (int i = 0; i < allList.size(); i++) {
					String measuretime = allList.get(i).get("measuretime")
							.substring(0, endLength);
					Map<String, String> eachAllMap = allList.get(i);
					for (int j = 0; j < finalList.size(); j++) {

						if (measuretime.equals(finalList.get(j).get(
								"measuretime"))) {
							if (eachAllMap.containsKey("heartrate")) {
								finalList.get(j).put("heartrate",
										eachAllMap.get("heartrate"));
							}
							if (eachAllMap.containsKey("bloodpressure")) {

								if (Integer.parseInt(eachAllMap.get("flag")) == MyConst.PRESSURE_H) {
									finalList.get(j).put("pressureH",
											eachAllMap.get("bloodpressure"));
								} else {
									finalList.get(j).put("pressureL",
											eachAllMap.get("bloodpressure"));
								}
							}
							break;

						}
					}

				}

				Collections.sort(finalList,
						new Comparator<Map<String, String>>() {
							public int compare(Map<String, String> arg0,
									Map<String, String> arg1) {
								return arg0.get("measuretime").compareTo(
										arg1.get("measuretime"));
							}
						});

				// 保存高压的值 默认值是110即当一天没有高压时添加默认值是110 最多显示60天数据
				double[] pressureHArr = new double[60];
				// 保存低压的值 默认值是80即当一天没有低压时添加默认值是80
				double[] pressureLArr = new double[60];
				// 保存高压或110：若高压>110的话保存110否则保存保存高压
				double[] pressureH_OR_LStandard = new double[60];
				// 保存低压或80：若低压<80保存80否则保存低压
				double[] pressureL_OR_HStandard = new double[60];

				// 心率列表70
				double[] plusArr = new double[60];

				for (int i = 0; i < finalList.size(); i++) {

					heartDateList.add(finalList.get(i).get("measuretime")
							.substring(showStartLength));
					if (!finalList.get(i).containsKey("heartrate")) {
						plusArr[i] = Double.parseDouble("80");// 默认值
						pressureL_OR_HStandard[i] = Double.parseDouble("80");
					} else {
						double lPressure = Double.parseDouble(finalList.get(i)
								.get("heartrate"));
						plusArr[i] = lPressure;
						if (lPressure <= 80) {
							pressureL_OR_HStandard[i] = 80;
						} else {
							pressureL_OR_HStandard[i] = lPressure;
						}
					}
					if (!finalList.get(i).containsKey("pressureH")) {
						pressureHArr[i] = Double.parseDouble("110");
						pressureH_OR_LStandard[i] = Double.parseDouble("110");
					} else {
						double hPressure = Double.parseDouble(finalList.get(i)
								.get("pressureH"));
						pressureHArr[i] = hPressure;
						if (hPressure >= 110) {
							pressureH_OR_LStandard[i] = 110;
						} else {
							pressureH_OR_LStandard[i] = hPressure;
						}
					}
					if (!finalList.get(i).containsKey("pressureL")) {
						pressureLArr[i] = Double.parseDouble("80");
					} else {
						pressureLArr[i] = Double.parseDouble(finalList.get(i)
								.get("pressureL"));
					}
				}

				List<double[]> plusPressureValues = new ArrayList<double[]>();
				plusPressureValues.add(plusArr);
				plusPressureValues.add(pressureHArr);// 1
				plusPressureValues.add(pressureH_OR_LStandard);// 2
				plusPressureValues.add(pressureL_OR_HStandard);// 3
				plusPressureValues.add(pressureLArr);// 4

				ll_catt_pluspressure_chart_view.removeAllViews();
				mChartView = new ChartViewProdutor(rootView.getContext())
						.getPlusPressureChart(plusPressureValues, heartDateList);
				ll_catt_pluspressure_chart_view.addView(mChartView);
			} else {
				Toast.makeText(this.getActivity(), "暂无数据", 0).show();
			}

		default:
			break;
		}

	}

	public void getOther() {

		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPagesize("50");
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("beginTime", otherBeginTime);
		data.put("endTime", otherEndTime);
		parameter.setData(data);

		new HttpServer().post(HttpCons.QUERY_PATIENT_SYMPTOM, parameter,
				otherHandler);

	}

	// 统计血压
	private void getPressure() {
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPagesize("50");
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("beginTime", plusBeginTime);
		data.put("endTime", plusEndTime);
		parameter.setData(data);

		new HttpServer().post(HttpCons.QUERY_BLOOD_PRESSURE_HEART_RATE,
				parameter, pressureHandler);

	}

	// 血糖
	private void getSugar() {
		TransferParameter parameter = new TransferParameter();
		parameter.setPagesize("50");
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("beginTime", sugarBeginTime);
		data.put("endTime", sugarEndTime);
		parameter.setData(data);

		new HttpServer().post(HttpCons.QUERY_BLOOD_GLUCOSE, parameter,
				sugarHandler);

	}

	// 心率
	private void getHeart() {
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPagesize("50");
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("beginTime", plusBeginTime);
		data.put("endTime", plusEndTime);
		parameter.setData(data);

		new HttpServer().post(HttpCons.QUERY_BLOOD_PRESSURE_HEART_RATE_VALUE,
				parameter, heartHandler);

	}

	// 初始化图表
	public void initChart() {
		ll_catt_pluspressure_chart_view.removeAllViews();
		ll_catt_sugar_chart_view.removeAllViews();

		List<double[]> values = new ArrayList<double[]>();
		List<String> dates = new ArrayList<String>();
		mChartView = new ChartViewProdutor(rootView.getContext())
				.getBloodChart(values, dates);
		ll_catt_sugar_chart_view.addView(mChartView);
		ll_catt_pluspressure_chart_view.addView(mChartView);

	}

	// 统计数据
	private void statisticsSugar(int type, String[] data) {
		popupWindow = new StatisticsPopupWindow(rootView.getContext(), type,
				data, isSugarDay, isplus_heart_Day);

		popupWindow.showAtLocation(main_history_ll, Gravity.CENTER, 0, 0);
	}

	@Override
	public void onClick(View arg0) {
		if (MyConst.getACCOUNT().equals("")) {

			View dialogView = initDataInputDialog(new DataDialogListener(), 0);
			if (null != dialogView)
				alertDialog = DialogUtil.showDialog(this.getActivity(),
						dialogView, true);
		} else {
			switch (arg0.getId()) {
			case R.id.tv_sugar_statistics:
				// 血糖统计
				Log.e("hdata", sugarBeginTime + " " + sugarEndTime);
				if (!TextUtils.isEmpty(sugarBeginTime)
						&& !TextUtils.isEmpty(sugarEndTime)) {
					TransferParameter parameter = new TransferParameter();
					// parameter.setPagesize("50");
					// parameter.setUsername(MyConst.getACCOUNT());
					// parameter.setCurrentPage("1");
					HashMap<String, Object> tpdata = new HashMap<String, Object>();
					tpdata.put("beginTime", sugarBeginTime);
					tpdata.put("endTime", sugarEndTime);
					tpdata.put("aliasAccount", MyConst.getACCOUNT());
					parameter.setData(tpdata);
					new HttpServer().post(HttpCons.QUERY_ONEORMORE_DAY_SUGAR,
							parameter, sugarStatisticsHandler);

				} else {
					Toast.makeText(this.getActivity(), "请选择时间", 0).show();
				}

				break;
			case R.id.et_sugar_begin_time:
				// 血糖开始时间
				datePickerDialog = new DatePickerDialog(
						MainHistoryDataFragment.this.getActivity(),
						SugarBeginDateSet,
						sugarBeginCalendar.get(Calendar.YEAR),
						sugarBeginCalendar.get(Calendar.MONTH),
						sugarBeginCalendar.get(Calendar.DAY_OF_MONTH));
				datePickerDialog.setTitle("开始时间");
				datePickerDialog.show();

				break;
			case R.id.et_sugar_end_time:
				// 血糖结束时间
				sugarPickerDialog = new DatePickerDialog(
						MainHistoryDataFragment.this.getActivity(),
						SugarEndDateSet, sugarEndCalendar.get(Calendar.YEAR),
						sugarEndCalendar.get(Calendar.MONTH),
						sugarEndCalendar.get(Calendar.DAY_OF_MONTH));
				sugarPickerDialog.setTitle("结束时间");
				sugarPickerDialog.show();
				break;
			case R.id.tv_pluspressure_statistics:
				// 血压统计
				if (!TextUtils.isEmpty(plusBeginTime)
						&& !TextUtils.isEmpty(plusEndTime)) {
					TransferParameter parameter = new TransferParameter();
					// parameter.setPagesize("50");
					// parameter.setUsername(MyConst.getACCOUNT());
					// parameter.setCurrentPage("1");
					HashMap<String, Object> tpdata = new HashMap<String, Object>();
					tpdata.put("beginTime", plusBeginTime);
					tpdata.put("endTime", plusEndTime);
					tpdata.put("aliasAccount", MyConst.getACCOUNT());
					parameter.setData(tpdata);
					new HttpServer().post(HttpCons.QUERY_HEART_RATE_PRESS,
							parameter, plusPressureStatisticsHandler);
				} else {
					Toast.makeText(this.getActivity(), "请选择时间", 0).show();
				}

				break;
			case R.id.et_pluspressure_begin_time:
				// 血压时间

				datePickerDialog = new DatePickerDialog(
						MainHistoryDataFragment.this.getActivity(),
						PlusPressureBeginDateSet,
						plusBeginCalendar.get(Calendar.YEAR),
						plusBeginCalendar.get(Calendar.MONTH),
						plusBeginCalendar.get(Calendar.DAY_OF_MONTH));
				datePickerDialog.setTitle("开始时间");
				datePickerDialog.show();
				break;
			case R.id.et_pluspressure_end_time:
				AlertDialog plusPickerDialog = new DatePickerDialog(
						MainHistoryDataFragment.this.getActivity(),
						PlusPressureEndDateSet,
						plusEndCalendar.get(Calendar.YEAR),
						plusEndCalendar.get(Calendar.MONTH),
						plusEndCalendar.get(Calendar.DAY_OF_MONTH));
				plusPickerDialog.setTitle("结束时间");
				plusPickerDialog.show();
				break;
			case R.id.tv_other_statistics:
				// 其他统计
				if (!TextUtils.isEmpty(otherBeginTime)
						&& !TextUtils.isEmpty(otherEndTime)) {
					TransferParameter parameter = new TransferParameter();
					parameter.setPagesize("50");
					parameter.setUsername(MyConst.getACCOUNT());
					parameter.setCurrentPage("1");
					HashMap<String, Object> tpdata = new HashMap<String, Object>();
					tpdata.put("beginTime", otherBeginTime);
					tpdata.put("endTime", otherEndTime);
					tpdata.put("aliasAccount", MyConst.getACCOUNT());
					parameter.setData(tpdata);
					new HttpServer()
							.post(HttpCons.NUMBEROF_NORMALANDABNORMAL_RATEOFTHEQUERYOTHERSYMPTOMS,
									parameter, otherStatisticsHandler);
				} else {
					Toast.makeText(this.getActivity(), "请选择时间", 0).show();
				}

				break;

			case R.id.et_other_begin_time:
				datePickerDialog = new DatePickerDialog(
						MainHistoryDataFragment.this.getActivity(),
						OtherBeginDateSet,
						otherBeginCalendar.get(Calendar.YEAR),
						otherBeginCalendar.get(Calendar.MONTH),
						otherBeginCalendar.get(Calendar.DAY_OF_MONTH));
				datePickerDialog.setTitle("开始时间");
				datePickerDialog.show();

				break;
			case R.id.et_other_end_time:
				AlertDialog otherPickerDialog = new DatePickerDialog(
						MainHistoryDataFragment.this.getActivity(),
						OtherEndDateSet, otherEndCalendar.get(Calendar.YEAR),
						otherEndCalendar.get(Calendar.MONTH),
						otherEndCalendar.get(Calendar.DAY_OF_MONTH));
				otherPickerDialog.setTitle("结束时间");
				otherPickerDialog.show();

				break;
			default:
				break;
			}
		}

	}

	boolean isSugar = true;
	boolean isPlus = true;
	DatePickerDialog.OnDateSetListener SugarBeginDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// 每次保存设置的日期

			sugarBeginCalendar.set(Calendar.YEAR, year);
			sugarBeginCalendar.set(Calendar.MONTH, monthOfYear);
			sugarBeginCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			ll_catt_sugar_chart_view.removeAllViews();
			et_sugar_begin_time.setText(+year + "-" + (monthOfYear + 1) + "-"
					+ dayOfMonth);
			et_sugar_end_time.setText(null);
		}
	};

	DatePickerDialog.OnDateSetListener SugarEndDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			int byear = sugarBeginCalendar.get(Calendar.YEAR);
			int bmonth = sugarBeginCalendar.get(Calendar.MONTH);
			int bday = sugarBeginCalendar.get(Calendar.DAY_OF_MONTH);
			int bDayNum = byear * 365 + bmonth * 30 + bday;
			int eDayNum = year * 365 + monthOfYear * 30 + dayOfMonth;
			if (bDayNum >= eDayNum) {
				Toast.makeText(MainHistoryDataFragment.this.getActivity(),
						"结束时间不能小于起始时间", 0).show();
				sugarEndCalendar = Calendar.getInstance();
				sugarEndTime = "";
				et_sugar_end_time.setText(null);
			} else {
				sugarEndCalendar.set(Calendar.YEAR, year);
				sugarEndCalendar.set(Calendar.MONTH, monthOfYear);
				sugarEndCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				sugarBeginTime = byear + "-" + (bmonth + 1) + "-" + bday;
				sugarEndTime = year + "-" + (monthOfYear + 1) + "-"
						+ dayOfMonth;

				et_sugar_begin_time.setText(sugarBeginTime);
				et_sugar_end_time.setText(sugarEndTime);
				if (eDayNum - bDayNum == 1) {
					isPlus = false;
					isSugar = true;
					getOneDayData(sugarBeginTime);
					isSugarDay = true;
				} else {
					getSugar();
					isSugarDay = false;
				}

			}

		}
	};

	DatePickerDialog.OnDateSetListener PlusPressureBeginDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// 每次保存设置的日期

			plusBeginCalendar.set(Calendar.YEAR, year);
			plusBeginCalendar.set(Calendar.MONTH, monthOfYear);
			plusBeginCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			ll_catt_pluspressure_chart_view.removeAllViews();
			et_pluspressure_begin_time.setText(+year + "-" + (monthOfYear + 1)
					+ "-" + dayOfMonth);
			et_pluspressure_end_time.setText(null);

		}
	};

	DatePickerDialog.OnDateSetListener PlusPressureEndDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			int byear = plusBeginCalendar.get(Calendar.YEAR);
			int bmonth = plusBeginCalendar.get(Calendar.MONTH);
			int bday = plusBeginCalendar.get(Calendar.DAY_OF_MONTH);
			int bDayNum = byear * 365 + bmonth * 30 + bday;
			int eDayNum = year * 365 + monthOfYear * 30 + dayOfMonth;
			if (bDayNum >= eDayNum) {
				Toast.makeText(MainHistoryDataFragment.this.getActivity(),
						"结束时间不能小于起始时间", 0).show();
				plusEndCalendar = Calendar.getInstance();
				et_pluspressure_end_time.setText(null);
			} else {
				plusEndCalendar.set(Calendar.YEAR, year);
				plusEndCalendar.set(Calendar.MONTH, monthOfYear);
				plusEndCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
				plusBeginTime = byear + "-" + (bmonth + 1) + "-" + bday;
				plusEndTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;

				et_pluspressure_begin_time.setText(plusBeginTime);
				et_pluspressure_end_time.setText(plusEndTime);

				if (eDayNum - bDayNum == 1) {
					isPlus = true;
					isSugar = false;
					getOneDayData(plusBeginTime);
					isplus_heart_Day = true;
				} else {
					getHeart();
					isplus_heart_Day = false;
				}

			}

		}
	};

	DatePickerDialog.OnDateSetListener OtherBeginDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// 每次保存设置的日期

			otherBeginCalendar.set(Calendar.YEAR, year);
			otherBeginCalendar.set(Calendar.MONTH, monthOfYear);
			otherBeginCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			et_other_begin_time.setText(+year + "-" + (monthOfYear + 1) + "-"
					+ dayOfMonth);
			et_other_end_time.setText(null);
			catt_hor_list.setAdapter(new HorizontalAdapter(
					MainHistoryDataFragment.this.getActivity(),
					new ArrayList<Map<String, Object>>(), popupWindow,
					main_history_ll, isSugarDay, isplus_heart_Day));

		}
	};

	DatePickerDialog.OnDateSetListener OtherEndDateSet = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			int byear = otherBeginCalendar.get(Calendar.YEAR);
			int bmonth = otherBeginCalendar.get(Calendar.MONTH);
			int bday = otherBeginCalendar.get(Calendar.DAY_OF_MONTH);
			int bDayNum = byear * 365 + bmonth * 30 + bday;
			int eDayNum = year * 365 + monthOfYear * 30 + dayOfMonth;
			if (bDayNum >= eDayNum) {
				Toast.makeText(MainHistoryDataFragment.this.getActivity(),
						"结束时间不能小于起始时间", 0).show();
				otherEndCalendar = Calendar.getInstance();
				et_other_end_time.setText(null);
			} else {

				otherEndCalendar.set(Calendar.YEAR, year);
				otherEndCalendar.set(Calendar.MONTH, monthOfYear);
				otherEndCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

				otherBeginTime = byear + "-" + (bmonth + 1) + "-" + bday;
				otherEndTime = year + "-" + (monthOfYear + 1) + "-"
						+ dayOfMonth;
				et_other_begin_time.setText(otherBeginTime);
				et_other_end_time.setText(otherEndTime);

				getOther();

			}

		}
	};

	public static Fragment newInstance() {
		return new MainHistoryDataFragment();
	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return false;
	}

	private View initDataInputDialog(DataDialogListener dataListener, int i) {
		LayoutInflater inflater = LayoutInflater.from(this.getActivity());
		View view = inflater.inflate(R.layout.dialog_input_daaa, null);
		TextView tv_catt_dialogLeft = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		tv_catt_dialogLeft.setOnClickListener(dataListener);
		TextView tv_catt_dialogRight = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		tv_catt_dialogRight.setOnClickListener(dataListener);
		return view;

	}

	public class DataDialogListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.tv_catt_dialogLeft:// 取消
				alertDialog.dismiss();
				break;
			case R.id.tv_catt_dialogRight:// 确定

				Intent personinfoIntent = new Intent(
						MainHistoryDataFragment.this.getActivity(),
						LoginActivity.class);
				MainHistoryDataFragment.this.getActivity().startActivity(
						personinfoIntent);
				alertDialog.dismiss();

			}
		}

	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			if (this.isInitViewCompleted) {
				if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
					isPlus = true;
					isSugar = true;
					Calendar calendar = Calendar.getInstance();
					int year = calendar.get(Calendar.YEAR);
					int month = calendar.get(Calendar.MONTH);
					int day = calendar.get(Calendar.DAY_OF_MONTH);

					sugarBeginTime = year + "-" + (month + 1) + "-" + day;
					plusBeginTime = sugarBeginTime;
					et_sugar_begin_time.setText(sugarBeginTime);
					et_pluspressure_begin_time.setText(plusBeginTime);
					calendar.add(Calendar.DAY_OF_MONTH, 1);
					year = calendar.get(Calendar.YEAR);
					month = calendar.get(Calendar.MONTH);
					day = calendar.get(Calendar.DAY_OF_MONTH);
					sugarEndTime = year + "-" + (month + 1) + "-" + day;
					plusEndTime = year + "-" + (month + 1) + "-" + day;
					et_sugar_end_time.setText(sugarEndTime);
					et_pluspressure_end_time.setText(plusEndTime);

					getOneDayData(CommonUtil.getFormatDate("yyyy-MM-dd",
							new Date()));

					if (!TextUtils.isEmpty(otherBeginTime)
							&& !TextUtils.isEmpty(otherEndTime)) {
						getOther();
					}
				}

			}
		} else {

		}
	}

	/**
	 * 得到一天的详细数据
	 * 
	 * @param dateStr
	 */
	private void getOneDayData(String dateStr) {
		TransferParameter parameter = new TransferParameter();
		HashMap<String, Object> tpdata = new HashMap<String, Object>();
		tpdata.put("measure", dateStr);
		parameter.setData(tpdata);
		new HttpServer().post(HttpCons.THE_QUERY_OF_DATA_IN_ADAY, parameter,
				oneDayAllHandler);

	}

}
